var express = require('express');
var router = express.Router();

/* GET home page. */
router.post('/getImage', async function(req, res){
  try{
    const prompt = req.body.prompt
    if(!prompt){
      res.json({msg: '参数错误'})
      return
    }
    const { Configuration, OpenAIApi } = require("openai");
    const configuration = new Configuration({
      apiKey: process.env.API_KEY 
    });
    const openai = new OpenAIApi(configuration);
    const response = await openai.createImage({
      prompt: prompt,
      n: 1,
      size: "256x256",
    });
    if(response.status == 200){
      res.json({url: response.data.data[0].url})
    }else{
      res.json({url: '请求失败'})
    }
  }catch(error){
    console.log(error)
    res.json({url: '请求异常'})
  }
})

router.post('/createCompletion', async function(req, res){
  try{
    const prompt = req.body.prompt
    const { Configuration, OpenAIApi } = require("openai");
    const configuration = new Configuration({
      apiKey: process.env.API_KEY 
    });
    const openai = new OpenAIApi(configuration);

    const response = await openai.createChatCompletion({
      model: "gpt-3.5-turbo",
      messages: [{"role": "user", "content": prompt}]
    });
    if(response.status == 200){
      res.json({text: response.data.choices[0].message.content})
    }else{
      res.json({text: '请求失败'})
    }
  }catch(error){
    console.log(error)
    res.json({text: '请求异常'})
  }
})


module.exports = router;
